﻿using System;
using System.Drawing;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Xnatlas.Serialization;
using Color = Microsoft.Xna.Framework.Color;

namespace Xnatlas
{
    public class GraphicsDeviceAtlas : BaseAtlas
    {
        public GraphicsDeviceAtlas(GraphicsDevice graphicsDevice, ContentManager content, int width, int height)
            : base(width, height)
        {
            Content = content;
            Texture = new Texture2D(graphicsDevice, width, height);
        }

        public GraphicsDeviceAtlas(ContentManager content, string fileName, StorageType storageType)
        {
            Content = content;
            Texture = content.Load<Texture2D>(fileName);
            SetSize(Texture.Width, Texture.Height);

            AtlasStore atlasStore = AtlasStoreSerializer.LoadFromFile(content.RootDirectory + @"\" + fileName, storageType);
            if (atlasStore.Width != Width || atlasStore.Height != Height)
            {
                throw new InvalidOperationException("Image and store mismatch on size!");
            }

            AppendStoreBitmaps(atlasStore);
            Lock();
        }

        public Texture2D Texture { get; set; }
        public ContentManager Content { get; set; }

        protected override ITextureWrapper GetTextureWrapper(string name, string data)
        {
            Texture2D rawTexture = Content.Load<Texture2D>(name);
            return new Texture2DTextureWrapper(rawTexture, data);
        }

        protected override void BlitTextureToAtlas(AtlasedTexture atlasedTexture)
        {
            Color[] colors = new Color[atlasedTexture.OriginalTexture.Width * atlasedTexture.OriginalTexture.Height];
            Texture2D texture = ((Texture2DTextureWrapper)atlasedTexture.OriginalTexture).Texture;
            texture.GetData<Color>(colors);
            Texture.SetData<Color>(0, atlasedTexture.AtlasAreaRectangle, colors, 0, colors.Length);
        }
    }
}